package glossos.ui;

import glossos.search.Searcher;
import glossos.tree.MatchPatternPredicate;
import org.apache.log4j.Logger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

public class CommandLineController {
	private Logger logger = Logger.getLogger("glossos.search");
    private Searcher searcher;

    public CommandLineController(Searcher searcher) {
		this.searcher = searcher;
    }

	public void run() throws IOException{
		BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
		while (true){
			patternSearch(reader);
		}
	}

	private void patternSearch(BufferedReader reader) throws IOException {
		System.out.print("pattern: ");
		String input = reader.readLine();
		String[] pattern =  input.split("\\s");
		if (!MatchPatternPredicate.isValidPattern(pattern)){
			System.out.println(" Please, enter a valid pattern. Only words and the character $ are accepted.");
			return;
		}
				
		long startTime = System.currentTimeMillis(); 
		List<String> result = searcher.sequencesMatching(pattern, 0, 10);
		long endTime = System.currentTimeMillis();
		logger.info("Search for '" + input + "' took " + (endTime - startTime) + " ms.");
		
		if (result.isEmpty())
			System.out.println("Pattern not found");
		for (String sequence : result) {
			printResults(sequence, searcher.frequency(sequence));
		}
		
	}

	private void printResults(String sequence, Integer frequency) {
		System.out.println(" " + sequence + "\t(" + frequency + " occurrences)");
	}
	
}
